/*******************************************************************************
 * Copyright (c) Jonathan Buck - jonbuck16@gmail.com
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *    jonbuck16@gmail.com - initial API and implementation
 *******************************************************************************/
package net.jonbuck.tassoo.ui.view;

import net.jonbuck.tassoo.eventmanager.EventManager;
import net.jonbuck.tassoo.eventmanager.EventManagerImpl;
import net.jonbuck.tassoo.eventmanager.events.TaskStoreClosedEvent;
import net.jonbuck.tassoo.eventmanager.events.TaskStoreOpenedEvent;
import net.jonbuck.tassoo.eventmanager.listener.TaskStoreClosedListener;
import net.jonbuck.tassoo.eventmanager.listener.TaskStoreOpenedListener;
import net.jonbuck.tassoo.model.Container;
import net.jonbuck.tassoo.model.provider.TassooItemProviderAdapterFactory;
import net.jonbuck.tassoo.persistence.dao.TassooDao;
import net.jonbuck.tassoo.persistence.dao.TassooDaoImpl;
import net.jonbuck.tassoo.persistence.dao.util.TassooDaoHelperUtil;
import net.jonbuck.tassoo.persistence.exception.TassooQueryException;
import net.jonbuck.tassoo.ui.nl.Messages;

import org.eclipse.emf.edit.ui.provider.AdapterFactoryContentProvider;
import org.eclipse.emf.edit.ui.provider.AdapterFactoryLabelProvider;
import org.eclipse.jface.action.GroupMarker;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.layout.TableColumnLayout;
import org.eclipse.jface.viewers.ColumnWeightData;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.ViewerComparator;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.ui.IMemento;
import org.eclipse.ui.IViewSite;
import org.eclipse.ui.IWorkbenchActionConstants;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.part.ViewPart;
import org.eclipse.ui.views.properties.IPropertySheetPage;
import org.eclipse.ui.views.properties.tabbed.ITabbedPropertySheetPageContributor;
import org.eclipse.ui.views.properties.tabbed.TabbedPropertySheetPage;

/**
 * 
 * 
 * @since 1.0.0
 */
public class ContainersView extends ViewPart implements ITabbedPropertySheetPageContributor, ISelectionChangedListener,
		TaskStoreOpenedListener, TaskStoreClosedListener {

	private static final String CONTAINER_SELECTION = "Containers.selection"; //$NON-NLS-1$

	private TassooItemProviderAdapterFactory adapterFactory;

	private EventManager eventManager = EventManagerImpl.getInstance();

	private TableViewer tableViewer;

	private IStructuredSelection selection;

	/** Internal instance of the TassooDao. */
	private TassooDao tassooDao = TassooDaoImpl.getInstance();

	private Table table;

	/**
	 * 
	 */
	public void saveState(IMemento memento) {
		if (selection == null || selection.isEmpty()) {
			return;
		}
		Container container = (Container) selection.getFirstElement();
		memento.putString(CONTAINER_SELECTION, container.getContainerName());
		super.saveState(memento);
	}

	/**
	 * 
	 */
	public ContainersView() {
		super();
	}

	/**
	 * 
	 */
	@SuppressWarnings("rawtypes")
	public Object getAdapter(Class adapter) {
		if (adapter == IPropertySheetPage.class)
			return new TabbedPropertySheetPage(this);
		return super.getAdapter(adapter);
	}

	/**
	 * 
	 */
	public void createPartControl(Composite parent) {
		TableColumnLayout tableColumnLayout = new TableColumnLayout();
		Composite composite = new Composite(parent, SWT.NONE);
		composite.setLayout(tableColumnLayout);
				
		table = new Table(composite, SWT.FULL_SELECTION);
		table.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));

		TableColumn valueColumn = new TableColumn(table, SWT.NONE);
		valueColumn.setText(Messages.containersview_tablecolumnlabel_value);
		tableColumnLayout.setColumnData(valueColumn, new ColumnWeightData(100));

		tableViewer = new TableViewer(table);
		tableViewer.setComparator(new ViewerComparator());
		tableViewer.setContentProvider(new AdapterFactoryContentProvider(adapterFactory));
		tableViewer.setLabelProvider(new AdapterFactoryLabelProvider(adapterFactory));
		if (tassooDao.isLoaded()) {
			tableViewer.setInput(tassooDao.getContainers());
		}
		tableViewer.addSelectionChangedListener(this);
		tableViewer.getTable().addListener(SWT.MeasureItem, new Listener() {
			public void handleEvent(Event event) {
				event.height = 20;
			}
		});

		MenuManager menuMgr = new MenuManager();
		menuMgr.add(new GroupMarker(IWorkbenchActionConstants.MB_ADDITIONS));
		getSite().registerContextMenu(menuMgr, tableViewer);

		Menu menu = menuMgr.createContextMenu(tableViewer.getControl());
		tableViewer.getControl().setMenu(menu);

		getSite().setSelectionProvider(tableViewer);

		tableViewer.setSelection(selection);
	}

	/**
	 * 
	 */
	public String getContributorId() {
		return getSite().getId();
	}

	/**
	 * 
	 */
	public void init(IViewSite site, IMemento memento) throws PartInitException {
		super.init(site, memento);
		adapterFactory = new TassooItemProviderAdapterFactory();
		eventManager.addListener(TaskStoreOpenedEvent.class, this);
		eventManager.addListener(TaskStoreClosedEvent.class, this);

		if (memento == null) {
			return;
		}
		String value = memento.getString(CONTAINER_SELECTION);
		if (value == null) {
			return;
		}

		try {
			if (tassooDao.isLoaded()) {
				selection = new StructuredSelection(TassooDaoHelperUtil.getContainerByValue(tassooDao, value));
			}
		} catch (TassooQueryException e) {
			// TODO Handle exception correctly
			e.printStackTrace();
		}
	}

	/**
	 * <p>
	 * <b>Event is processed when the current task store is closed.</b>
	 * </p>
	 */
	public void processTaskStoreClosedEvent() {
		tableViewer.setInput(new Object[0]);
	}

	/**
	 * <p>
	 * <b>Event is processed when a task store is opened within the
	 * application.</b>
	 * </p>
	 */
	public void processTaskStoreOpenedEvent() {
		if (tassooDao.isLoaded()) {
			tableViewer.setInput(tassooDao.getContainers());
		}
	}

	/**
	 * 
	 */
	public void setFocus() {
	}

	/**
	 * 
	 */
	public void selectionChanged(SelectionChangedEvent event) {
		selection = (IStructuredSelection) tableViewer.getSelection();
	}

}
